import type { Pod, PodList } from "@/views/domain/kubeHud/api/k8s/types";

import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import { onMounted, ref, type Ref } from "vue";
import type { PodDetails, PodQuery } from "@/views/domain/kubeHud/api/k8s/pod";
import type { PromiseRes } from "@/api/response";
import { useRoute } from "vue-router";
const { podRepo } = useK8SApi();

class PodProvider extends SourceMan<Pod> {
  podDetails = ref<PodDetails>();

  get podList(): Ref<Pod[]> {
    return this.srcList;
  }

  // 获取节点列表
  getPods = async (req?: PodQuery): PromiseRes<PodList> => {
    const res = await podRepo.getPodList({
      ...(req || this.searchQuery.value),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res.ok) {
      this.continue = res.data.metadata.continue;
      this.srcList.value = res.data.items;
      this.pager.total.value =
        res.data.metadata.remainingItemCount ?? res.data?.items?.length;
    }
    return res;
  };

  // 获取节点详情
  getPodDetails = async (query: { namespace?: string; name?: string }) => {
    const res = await podRepo.getPodDetail(query);
    if (res.ok) {
      this.podDetails.value = res.data;
      // this.srcYamlContent.value = this.objectToYaml(res.data);
      // this.yamlDialog.value = true;
    }
  };

  // 更新节点
  updatePod = async (data?: { namespace?: string; name?: string }) => {
    const res = await podRepo.updatePod(data);
    if (res.ok) {
      this.refreshPodList();
    }
  };

  // delete
  deletePod = async (query?: { namespace?: string; name?: string }) => {
    const res = await podRepo.deletePod(query);
    if (res.ok) {
      this.refreshPodList();
    }
  };

  refreshPodList = async () => {
    this.continue = undefined;
    await this.getPods({});
  };

  getPodLog = async (query: { namespace?: string; name?: string }) => {
    // TODO: implement this
    console.log("getPodLog", query);
    return;
  };

  getPodContainers = async (query?: Pod) => {
    // TODO: implement this
    console.log("getPodContainers", query);
    return;
  };
}

// export default new PodProvider();

export const usePodProvider = () => {
  const route = useRoute();
  const provider = new PodProvider();

  // 根据路由获取pod详情
  const getPodDetailsFromRoute = async () => {
    return provider.getPodDetails({
      namespace: `${route.query.namespace ?? ""}`,
      name: `${route.query.name ?? ""}`
    });
  };

  onMounted(getPodDetailsFromRoute);
  return {
    ...provider,
    getPodDetailsFromRoute,
    route
  };
};
